package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.heima.article.listener.ArticlesCountListener;
import com.heima.article.service.ArticleCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.KafkaConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.kafka.MessageDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @author 熏橙橙
 * @version 1.0
 * @date 2023-08-03 11:03
 */
@Service
public class ArticleCollectionServiceImpl implements ArticleCollectionService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ArticlesCountListener articlesCountListener;
    /**
     * 收藏文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        //数据校验
        if (dto==null||dto.getEntryId()==null||dto.getType()==(short)1
                ||dto.getOperation()==null||user==null
                ||user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //数据处理   --- collection + userId + 文章id
        String key = BehaviorConstants.COLLECTION + user.getId() +"_"+ dto.getEntryId();

        //存入redis
        if (dto.getOperation()==0){
            cacheService.set(key, JSON.toJSONString(dto));
        }else {
            cacheService.delete(key);
        }
        MessageDto messageDto = MessageDto.builder()
                .apArticleId(dto.getEntryId().toString())
                .count(dto.getOperation() == 0 ? 1 : -1)
                .type(3)
                .build();
        articlesCountListener.cont(JSON.toJSONString(messageDto));
        return ResponseResult.okResult(200,dto.getOperation()==0?"收藏成功":"取消收藏成功");
    }
}
